<?php

class Certificate {

	static public function createCsr($username, $email) {
		$dn = array(
			"countryName" => "BE",
			"stateOrProvinceName" => "not specified",
			"localityName" => "not specified",
			"organizationName" => $username,
			"organizationalUnitName" => "payment",
			"commonName" => $username,
			"emailAddress" => $email
		);
		
		// Generate a new private (and public) key pair
		$privkey = openssl_pkey_new();
		
		// Generate a certificate signing request
		return openssl_csr_new($dn, $privkey);
	}
	
	static public function signCsr($csr, $passPhrase) {
	
		$certFile = "cacert/ca.pem";
		$keyFile= "key/ca.key";

		$errorCount = 0;
		
		flush();
		$fp = fopen($keyFile, "r") or $errorCount++;
		$myKey = fread($fp, filesize($keyFile)) or $errorCount++;
		fclose($fp) or $errorCount++;
		if ($errorCount) {
			print "FATAL: an error occured in the script. Possibly due to inadequate file permissions.";
		}
		
		flush();
		$privkey = openssl_pkey_get_private($myKey, $passPhrase);
		
		flush();
		$fp = fopen($certFile, "r") or $errorCount++;
		$myCert = fread($fp, filesize($certFile)) or $errorCount++;
		fclose($fp) or $errorCount++;
		if ($errorCount) {
			print "FATAL: an error occured in the script. Possibly due to inadequate file permissions.";
		}
		
		flush();
		$scert = openssl_csr_sign($csr, $myCert, $privkey, 365);
		flush();
		
		flush();
		openssl_x509_export($scert, $theirCert);
		
		return $theirCert;
	}
	
	static public function createX509($username, $email, $passPhrase) {
		return Certificate::signCsr(Certificate::createCsr($username, $email),$passPhrase);
	}

}

?>